package com.station.xml;

import java.lang.reflect.Field;

/**
 * SAX解析使用，反射对象，依据标注注入属性值
 * @author hehc
 *
 */
public class XmlObjectHelper {

    /**
     * 根据xml标签元素将值注入对象对应Field，支持列表展示数据
     * @param obj 被注入对象
     * @param str 值
     * @param currentEleName xml标签（Field Name）
     */
	public static void parserObject(Object obj, String str, String currentEleName) {
		if (obj == null) return;
		Field[] flds = obj.getClass().getDeclaredFields();
		for (Field fld : flds) {
			if (!fld.isAnnotationPresent(AnGetfunc.class)) {
				continue;
			}
			AnGetfunc axh = fld.getAnnotation(AnGetfunc.class);
			if (axh.need()) {
				if (fld.getName().equals(currentEleName)) {
					try {
						fld.setAccessible(true);
						fld.set(obj, str);
						//如果是列表展示，注入列表显示字段
						if(obj instanceof ListSupport){
							ListSupport ls = (ListSupport)obj;
							if(axh.viewType().equals(ListSupport.ListItem.ANNOTATION_ID)){
								ls.getListItem().setId(str);
							}else if(axh.viewType().equals(ListSupport.ListItem.ANNOTATION_TITLE)){
								ls.getListItem().setTitle(str);
							}else if(axh.viewType().equals(ListSupport.ListItem.ANNOTATION_SUMMARY)){
								ls.getListItem().setSummary(str);
							}else if(axh.viewType().equals(ListSupport.ListItem.ANNOTATION_TAG)){
								ls.getListItem().setTag(str);
							}
						}
					}catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
					break;

				}
			}
		}
	}
	
	/**
	 * 初始化子对象属性(必须有Annotation)
	 * @param obj
	 * @param fieldName
	 */
	public static Object initFieldClazzObject(Object obj, String fieldName){
		Object fieldObj = null;
		if (obj == null) return null;
		try {
			Field fld = obj.getClass().getField(fieldName);
			if (!fld.isAnnotationPresent(AnGetfunc.class)) {
				return null;
			}
			AnGetfunc axh = fld.getAnnotation(AnGetfunc.class);
			if (axh.need()) {
				String clazz = axh.clazz();
				if(clazz != null && !clazz.equals("default")){
					fieldObj = Class.forName(clazz).newInstance();
				}
			}
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e){
			e.printStackTrace();
		}
		return fieldObj;
	}
}
